package com.wus.common.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wus.common.core.account.AccountThreadLocal;
import com.wus.common.core.domain.user.AccountInfo;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @Description: 数据表字段自动填充配置
 * @Author: wus
 * @Date: 2024/7/25 23:03
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        Date currentDate = new Date();
        setFieldValByName("createTime", currentDate, metaObject);
        setFieldValByName("updateTime", currentDate, metaObject);
        // 注意不需登录的情况
        AccountInfo loginUser = AccountThreadLocal.get();
        if (loginUser != null) {
            setFieldValByName("createDept", loginUser.getDeptId(), metaObject);
            setFieldValByName("createBy", loginUser.getUserId(), metaObject);
            setFieldValByName("updateBy", loginUser.getUserId(), metaObject);
        } else {
            this.printWarnMsg();
        }
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", new Date(), metaObject);
        // 注意不需登录的情况
        AccountInfo loginUser = AccountThreadLocal.get();
        if (loginUser != null) {
            setFieldValByName("updateBy", loginUser.getUserId(), metaObject);
        } else {
            this.printWarnMsg();
        }
    }

    private void printWarnMsg() {
        log.warn("没获取到用户登录信息");
    }
}
